package org.lalib.controller.action;

import org.lalib.acquire.IControllerAction;
import org.lalib.command.CookerCommand;
import org.lalib.command.WaiterCommand;
import org.lalib.controller.form.CMobileLoginForm;
import org.lalib.controller.service.CHistoricalValueService;
import org.lalib.entity.object.EHistoricalValue;
import org.lalib.entity.object.EItem;
import org.lalib.entity.object.EUser;
import org.lalib.util.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

@Scope("request")
@Controller("cMobileLoginAction")
public class CMobileLoginAction implements IControllerAction {

	private static final long serialVersionUID = 1L;

	@Autowired
	CMobileLoginForm cMobileLoginForm;

	@Autowired
	PasswordUtil passwordUtil;

	@Autowired
	CHistoricalValueService cHistoricalValueService;

	public void clear() {
		cMobileLoginForm.setErrorMessage(false);
	}

	@SuppressWarnings("rawtypes")
	public String login() {
		String username = cMobileLoginForm.getUsername();
		String password = cMobileLoginForm.getPassword();
		String loginType = cMobileLoginForm.getLoginType();
		String hashedPassword = passwordUtil.hash(password);

		EItem item = cHistoricalValueService.getItemFromStringValue("username", username);
		if (item == null) {
			cMobileLoginForm.setErrorMessage(true);
			return null;
		}

		EHistoricalValue passwordValue = cHistoricalValueService.getValue(item, "password");

		if (passwordValue == null || !passwordValue.getCore().toString().equals(hashedPassword)) {
			cMobileLoginForm.setErrorMessage(true);
			return null;
		}

		EUser user = (EUser) item;
		if (loginType.equals("true") && user.getUserGroup().getName().equals("Waiter")) {
			reset();
			return new WaiterCommand(user).execute();
		} else if (user.getUserGroup().getName().equals("Cooker") && loginType.equals("false")) {
			reset();
			return new CookerCommand(user).execute();
		}

		cMobileLoginForm.setErrorMessage(true);
		return null;
	}

	private void reset() {
		cMobileLoginForm.setPassword("");
		cMobileLoginForm.setUsername("");
		cMobileLoginForm.setLoginType("");
	}
}